package com.rasou.cglib;

import net.sf.cglib.proxy.MethodProxy;

import javax.interceptor.InvocationContext;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Map;

public class InvocationContextImplByCglib implements InvocationContext {
    private final Object target;

    private final Method method;

    private Object[] params;

    private Map<String, Object> contextData;

    private final MethodProxy methodProxy;

    public InvocationContextImplByCglib(Object target, Method method, MethodProxy methodProxy, Object[] params) {
        this.target = target;
        this.method = method;
        this.params = params;
        this.methodProxy = methodProxy;
    }

    @Override
    public Object getTarget() {
        return this.target;
    }

    @Override
    public Object getTimer() {
        return null;
    }

    @Override
    public Method getMethod() {
        return this.method;
    }

    @Override
    public Constructor<?> getConstructor() {
        Constructor<?> constructor = null;
        try {
            constructor = this.target.getClass().getConstructor();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return constructor;
    }

    @Override
    public Object[] getParameters() {
        return this.params;
    }

    @Override
    public void setParameters(Object[] params) {
        this.params = params;
    }

    @Override
    public Map<String, Object> getContextData() {
        return this.contextData;
    }

    @Override
    public Object proceed() throws Exception {
        try{
            return methodProxy.invokeSuper(getTarget(), getParameters());
        } catch (Throwable e) {
            throw new Exception(e);
        }
    }
}
